package com.blue.base.security.config;

import com.blue.base.security.api.AuthService;
import com.blue.base.security.exception.AuthFailLoginHandler;
import com.blue.base.security.exception.AuthSuccessLoginHandler;
import com.blue.base.security.exception.EntryPointRejectHandler;
import com.blue.base.security.filters.JwtAuthorizationTokenFilter;
import com.blue.base.security.filters.RequestPermissionRuleFilter;
import com.blue.base.security.filters.UsernamePasswordAuthFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * security 核心配置
 *
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Component
@EnableWebSecurity
public class SecurityWebConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityAuthConfig securityConfig;

    @Autowired
    ObjectProvider<AuthService> authServiceObjectProvider;

    @Autowired
    private ObjectProvider<UserDetailsService> userDetailsServiceObjectProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 禁用cors防护
        http.csrf().disable()
                .authorizeRequests()
                // 无条件忽略配置不拦截的url
                .antMatchers(StringUtils.join(securityConfig.getSkipUrl(), ",").split(",")).permitAll()
                // OPTIONS请求全部放行
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // 默认拦截所有未登录的请求【一定要做注意放在antMatchers()之后，否则会拦截所有url】
                .anyRequest().authenticated()
                .and()
                // 全局不创建session[不使用session缓存获取context上下文]
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 开启cookie储存用户信息，并设置有效期为14天，指定cookie中的密钥
                .rememberMe().tokenValiditySeconds(securityConfig.getCookieTtl()).key(securityConfig.getCookieKey())
                .and()
                .logout().disable()
                // 端点访问失败处理器
                .exceptionHandling().authenticationEntryPoint(new EntryPointRejectHandler());
        // 需要我们在config方法里面配置provider，如果是自己new的管理器，也是可以UsernamePasswordAuthManager
        UsernamePasswordAuthFilter authFilter = new UsernamePasswordAuthFilter(securityConfig, authenticationManager());
        authFilter.setAuthenticationSuccessHandler(new AuthSuccessLoginHandler(authServiceObjectProvider.getIfAvailable()));
        authFilter.setAuthenticationFailureHandler(new AuthFailLoginHandler());
        http.addFilterAt(authFilter, UsernamePasswordAuthenticationFilter.class);
        // token过滤器
        JwtAuthorizationTokenFilter jwtAuthTokenFilter = new JwtAuthorizationTokenFilter(authServiceObjectProvider.getIfAvailable(), securityConfig);
        http.addFilterBefore(jwtAuthTokenFilter, UsernamePasswordAuthenticationFilter.class);
        //有动态权限配置时添加动态权限校验过滤器
        RequestPermissionRuleFilter permissionRuleFilter = new RequestPermissionRuleFilter(authServiceObjectProvider.getIfAvailable());
        http.addFilterBefore(permissionRuleFilter, FilterSecurityInterceptor.class);
    }

    /**
     * 静态资源配置过滤
     */
    @Override
    public void configure(WebSecurity webSecurity) {
        webSecurity.ignoring().antMatchers(StringUtils.join(securityConfig.getSkipFile(), ",").split(","));
        webSecurity.ignoring().antMatchers(securityConfig.getLogoutUrl());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置用户登录查询校验类
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServiceObjectProvider.getIfAvailable())
                .passwordEncoder(passwordEncoder());
    }

}
